import { defineStore } from 'pinia'
import { Local } from '@/assets/utils/storage'
import { config } from '@/config'
const local = new Local()

const historyKey: string = 'searchHistory'

const state = () => {
    return {
        historyList: [] as Array<string>,
        visible: false as boolean,
        isFocus: false as boolean
    }
}

export const searchStore = defineStore('search', {
    state,
    getters: {
        historyInstance: state => {
            return state.historyList.length ? state.historyList : local.get(historyKey)
        }
    },
    actions: {
        add(val: string) {
            const data = local.get(historyKey)
            const num: number = config.searchCacheNum - 1
            // 超过9个删除最后一个
            if (this.historyList && this.historyList.length > num) {
                local.delete(historyKey, -1)
            }
            local.add(historyKey, data ? val : [val])
            this.historyList = local.get(historyKey)
        },
        delete(index: number) {
            local.delete(historyKey, index)
            this.historyList = local.get(historyKey)
        },
        remove() {
            local.remove(historyKey)
            this.historyList = []
        },
        setVisible(val: boolean) {
            this.visible = val
        },
        setFocus(val: boolean) {
            this.isFocus = val
        }
    }
})